package com.elean.pms.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常拦截处理类,处理系统出现的各种异常，并统一封装返回提示
 * @author zzw
 *
 */
@RestController
public class ErrorControllerHandler implements ErrorController {
	@Override
	public String getErrorPath() {
		return "/error";
	}

	private ErrorAttributes errorAttributes;

	@Autowired
	public ErrorControllerHandler(ErrorAttributes errorAttributes) {
		this.errorAttributes = errorAttributes;
	}

	/**
	 * ====================================================================
	 *函 数 名： @param resp
	 *函 数 名： @param req
	 *函 数 名： @return
	 *功 能： 在进入Controller之前，譬如请求一个不存在的地址，404错误。 
	----------------------------------------------------------------------
	 */
	@RequestMapping(value = "/error")
	public ResponseEntity error(HttpServletRequest req) {
		int code = 500;
		String message = "服务器内部错误";
		Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");
        if(statusCode == 401){
        	code = 401;
        	message = "未授权";
        }else if(statusCode == 404){
        	code = 404;
        	message = "请求路径出错";
        }else if(statusCode == 403){
        	code = 403;
        	message = "服务器拒绝请求";
        }else if(statusCode == 250){
			code = 250;
			message = "重复提交";
		}
		ResponseEntity r = ResponseEntity.build(code, message, null);
		return r;
	}
}
